package main

import (
	"fmt"
	"context"
	"etcd-discovery/pkg/discovery"
	pb "etcd-discovery/proto"
	"log"
	"net"
	"strconv"

	"github.com/google/uuid"
	"google.golang.org/grpc"
	"google.golang.org/grpc/balancer/roundrobin"
)

const (
	appID = "sv3"
	PORT  = "9031"
)

type Sv3Service struct {
	UUID      string
	sv1Client pb.Sv1ServiceClient
}

func (s *Sv3Service) Sv3Concat(ctx context.Context, r *pb.Sv3Request) (*pb.Sv3Response, error) {
	resp ,err := s.sv1Client.Sv1Concat(ctx,&pb.Sv1Request{Request: "sv3 call sv1"})
	if err != nil{
		fmt.Println("sv3 call sv1 err", err)
		return nil,err
	}else{
		fmt.Println("sv3 call sv1 ok", resp.Response)
	}
	return &pb.Sv3Response{Response: s.UUID + ":" + r.Request}, nil
}

func main() {
	dis := discovery.New(&discovery.Config{
		Nodes: []string{
			"127.0.0.1:2379",
		},
		Prefix: "default",
		Lease:  3,
	})
	server := grpc.NewServer()
	sv3 := NewSv3Service()
	pb.RegisterSv3ServiceServer(server, sv3)
	lis, err := net.Listen("tcp", ":"+PORT)
	if err != nil {
		log.Fatalf("net.Listen err: %v", err)
	}
	dis.Register(&discovery.Instance{
		AppID:    appID,
		Hostname: sv3.UUID,
		Addrs: []string{
			"grpc://" + "127.0.0.1" + ":" + PORT,
		},
		Metadata: map[string]string{
			"weight": strconv.FormatInt(10, 10),
		},
	})
	server.Serve(lis)
}

func NewSv3Service() *Sv3Service {
	var sv3 Sv3Service
	uuid := uuid.New().String()
	sv3.UUID = uuid

	sv1_targer := "etcd://default/sv1"
	sv1_conn, err := grpc.DialContext(context.Background(), sv1_targer,
		[]grpc.DialOption{
			grpc.WithInsecure(),
			grpc.WithBalancerName(roundrobin.Name),
		}...)
	if err != nil {
		panic(err)
	}
	sv3.sv1Client = pb.NewSv1ServiceClient(sv1_conn)
	return &sv3
}
